package server;

import java.io.*;
import java.net.*;
import java.util.logging.*;
import javax.xml.bind.*;

import shared.Cal;
import shared.Task;
import shared.User;

public class SimpleTcpServer {
	//Create String containing the path to task XML
	private static String xmlPath = "data/task-manager-xml.xml"; 
	private static String xmlSavePath = "data/task-manager-xml-out.xml"; 
	
	//Create Cal object for data
	private static Cal data;
	
	//Variables for streaming
	private static DataOutputStream outputStream;
	private static DataInputStream dataInputStream;
	
    public static void main(String args[]) {             
    	//Create server
        try {
        	//Load xml data
        	data = Cal.createCal(xmlPath);
        	System.out.println("Data on server created");

            // create a server socket listening at port 7896
            int serverPort = 7896;
            ServerSocket serverSocket = new ServerSocket(serverPort);

            // Server starts accepting requests.
            // This is blocking call, and it wont return, until there is request from a client.
            Socket socket = serverSocket.accept();
            
            // Get the input stream to receive data sent by client. 
            // Based on the type of data we want to read, we will open suitable input stream.  
            dataInputStream = new DataInputStream(socket.getInputStream());

            // Read the String data sent by client at once using readUTF,
            // Note that read calls also blocking and wont return until we have some data sent by client. 
            String message = dataInputStream.readUTF(); // blocking call
            outputStream = new DataOutputStream(socket.getOutputStream());
            if(message.equalsIgnoreCase("put")) {
            	//Send request
                outputStream.writeUTF(message);   
                
                //Receive data
                dataInputStream = new DataInputStream(socket.getInputStream());   
                System.out.println("Data received from client");
                System.out.println("Data:");
                System.out.println(dataInputStream.readUTF());
                
                //Create Cal object from received data
                Cal receivedDate = Cal.createCal((InputStream) dataInputStream);
                System.out.println("Cal from received data created");
                
                //Add users if not in data already
                for (User user: receivedDate.users) {
                	if(!data.users.contains(user)) {
                		data.users.add(user);
                	}
                }                
                //Add tasks if not in data already
                for (Task task: receivedDate.tasks) {
                	if(!data.tasks.contains(task)) {
                		data.tasks.add(task);
                	}
                }
                
            } else if(message.equalsIgnoreCase("get")) {
                outputStream.writeUTF(message);               	
            }  else if(message.equalsIgnoreCase("delete")) {
                outputStream.writeUTF(message);               	
            }  else {
                outputStream.writeUTF("Unrecognized command");               	
            } 
            outputStream.flush();

            
            Cal.saveCal(data, xmlSavePath);
            socket.close();

        } catch (IOException ex) {
            Logger.getLogger(SimpleTcpServer.class.getName()).log(Level.SEVERE, null, ex);

            System.out.println("error message: " + ex.getMessage());
        } catch (JAXBException e) {
			e.printStackTrace();
		}  finally {		
		}
    }
}